package com.zxh.fliter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zxh.utils.StringUtils;



public class CharSetFilter implements Filter {
	public String encode="";
	public String includeString = "";
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest hrerequest = (HttpServletRequest)req;
		HttpServletResponse hresponse = (HttpServletResponse) resp;
		req.setCharacterEncoding(encode);
		resp.setCharacterEncoding(encode);//设置请求编码格式
		resp.setContentType("text/html;charset=utf-8");//设置响应的编码格式
		HttpSession session  = hrerequest.getSession();
		
		
		
		//获取当前请求
		String url = hrerequest.getRequestURI().toString();
		String[] urls = includeString.split(",");//逗号分隔转成数组
		System.out.println(url);
		if(StringUtils.isExitsUrl(url, urls)){
			chain.doFilter(hrerequest, hresponse);//把请求交给下一个内容
		}else{
			if(session.getAttribute("applicant_id")==null){
				hresponse.sendRedirect("login.jsp");
			}else{
				chain.doFilter(hrerequest, hresponse);//把请求交给下一个内容
			}
		}
		
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		encode = config.getInitParameter("encode");//获取初始化参数
		includeString = config.getInitParameter("includeString");
		System.out.println("执行初始化操作");
		
	}
		
}
